/**
 * Created by apple on 16/3/31.
 */
class Controller {
    constructor (systemService, uiNotification, statusMap, openMode, $modalInstance, node, $timeout) {
        "ngInject"
        this.uiModal = $modalInstance;
        this.service = systemService;
        this.notify  = uiNotification;
        this.timeout = $timeout;
        this.status  = statusMap;
        this.openMode= openMode;
        this.type    = node.type;
        this.item    = node;
        this.isEdit  = node.item ? true : false;
        this.query   = this.isEdit ? 'update' : 'insert';
        this.data    = this.isEdit ? angular.copy(node.item) : {
            statusCd : "S0A",
            sysCode  : node.sysCode,
            openMode : "1100"
        };
        if (!this.isEdit) {
            this.type == 'menu' ? angular.extend(this.data, {
                parMenuId: node.pid,
                menuIndex: 0
            }) : angular.extend(this.data, {
                menuId: node.pid
            })
        }
    }

    checkValid (field) {
        if ( field.$pristine ) {
            field.$pristine = false;
        }
    }

    checkSame (type) {
        if (!this.isEdit) {
            if (this.data[type + 'Name']) {
                let param = type === 'comp' ? { compName: this.data.compName, menuId: this.item.pid, statusCd: 'S0A'} : { menuName: this.data.menuName, parMenuId: this.item.pid, statusCd: 'S0A'}
                if (this.checking) return;
                this.checking = true;
                this.timeout(() => {
                    this.service.checkExist(type, param).then((res) => {
                        this.checking = false;
                        this.isSame = res.data;
                        if (res.data) {
                            this.notify.error({
                                'title'  : '提示',
                                'message': '存在同名'+ (type === 'comp'? '控件': '菜单') +', 不可重复添加!'
                            });
                        }
                    })
                }, 250)
            }
        }
    }

    save () {
        if ( this.submitting ) return;
        this.submitting = true;

        this.service[this.query](this.type, this.data).then((r) => {
            if (this.query == 'insert') {
                this.data.id = r.data;
                this.data[this.type + 'Id'] = r.data;
            }
            this.uiModal.close(this.data);
            this.notify.success({
                'title'  : '提示',
                'message': '操作成功!'
            });
        }).catch((data) => {
            this.notify.error({
                'title'  : '提示',
                'message': '操作失败. ' + (data.resultMsg ? data.resultMsg : '')
            });
        }).finally(() => {
            // 隐藏 loading
            this.submitting = false;
        });
    }

    cancel () {
        this.uiModal.dismiss('cancel')
    }
}

export default Controller;